package org.wabson.alfresco.translations.bean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.wabson.alfresco.translations.BlobInfoDateComparator;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;

public class BlobstoreJarListLoader implements JarListLoader {

	@Override
	public List<Jarfile> getJars()
	{
		ArrayList<Jarfile> jars = new ArrayList<Jarfile>();
		
		   //BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		   BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
		   Iterator<BlobInfo> blobs = blobInfoFactory.queryBlobInfos();
		   ArrayList<BlobInfo> blobList = new ArrayList<BlobInfo>();
		   while (blobs.hasNext())
		   {
		       blobList.add(blobs.next());
		   }
		   Collections.sort(blobList, new BlobInfoDateComparator());
		
		for (BlobInfo info : blobList)
		{
			Jarfile jar = new Jarfile(info.getBlobKey().getKeyString(), info.getFilename());
			jar.setCreationDate(info.getCreation());
			jar.setSize(info.getSize());
			jars.add(jar);
		}
		return jars;
	}

	@Override
	public Jarfile getJar(String id)
	{
        BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
        BlobInfo blobInfo = blobInfoFactory.loadBlobInfo(new BlobKey(id));
        if (blobInfo != null)
        {
            Jarfile jar = new Jarfile(id, blobInfo.getFilename());
            jar.setCreationDate(blobInfo.getCreation());
            jar.setSize(blobInfo.getSize());
            return jar;
        }
        else
        {
        	return null;
        }
	}

}
